package ch.schlegl.fastsvn;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;

import ch.schlegl.fastsvn.json.Node;

@Path("nodes")
public class SvnNodesResource extends SvnClient {


    public SvnNodesResource() throws IOException {
        super();
    }

    @GET
	@Produces(MediaType.APPLICATION_JSON)
	public synchronized List<Node> getSubPaths(@QueryParam("id") String id,
			@QueryParam("node") String node) {
		System.out.println(id + " -> " + node);
        List<Node> subPaths = new ArrayList<Node>();
        if("root".equals(id)) {
            for(String rootUrl : rootUrls) {
                subPaths.add(new Node(rootUrl, rootUrl, Node.NodeType.FOLDER, false));
            }
            return subPaths;
        }
		try {
			ensureConnected(id);
			Collection<SVNDirEntry> entries = repository.getDir(node.replace(findRootUrl(id), ""), -1, null, (Collection) null);
			for (SVNDirEntry dirEntry : entries) {
				if(SVNNodeKind.DIR.equals(dirEntry.getKind())) {
					subPaths.add(createFolder(dirEntry));
				} else {
					subPaths.add(createFile(dirEntry));
				}
			}
		} catch (SVNException e) {
			e.printStackTrace();
		}
		return subPaths;
	}

	private Node createFolder(SVNDirEntry dirEntry) {
		return new Node(dirEntry.getURL().toString(), dirEntry.getName(), Node.NodeType.FOLDER, false);
	}

	private Node createFile(SVNDirEntry dirEntry) {
		return new Node(dirEntry.getURL().toString(), dirEntry.getName(), Node.NodeType.FILE, true);
	}
}